//index.js
//获取应用实例
var wxpay = require('../../utils/pay.js');
var util = require('../../utils/util.js');
var app = getApp()

Page({
  data: {
    mallName: "",
    selList: '',
    confirmOrder: {},
    curAddressData: null,//收货地址
    allCoupon: [],//所有能用的优惠券
    curCoupon: null,//当前优惠券
    hasPay: false,
    storeid: app.globalData.storeId,
    cash: 0,
    choosecash: 2,
    selectImg: "/images/nav/off.png",
    showAdress:true,
    myOrderData:{}
  },

  //选择取餐方式
  selectType: function (e) {
    let Img = this.data.selectImg;
    let showAdress = this.data.showAdress;
    if (Img == "/images/nav/off.png"){
      Img = "/images/nav/on.png";
      showAdress = false;
    }else{
      Img = "/images/nav/off.png"
      showAdress = true;
    }
    this.setData({
      selectImg: Img,
      showAdress: showAdress
    })
    this.confirmOrder()
  },

  //获取账户余额
  getUserCash: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/UserCash/GetUserCash?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cash: res.data.Data.Cash
          })
        }
      }
    })
  },
  onShow: function (e) {
    this.initShippingAddress();
    var c = wx.getStorageSync(this.data.selList);
    if (c) {
      this.setData({
        curCoupon: c
      })
      wx.clearStorageSync(this.data.selList);
    }
    this.getUserCash()
  },
  onLoad: function (e) {
    var that = this;
    var selList = e.sl;
    var mallName = wx.getStorageSync('mallName')
    if (mallName){
      that.setData({ mallName: mallName });
    }
    that.setData({ selList: selList});
  },
  confirmOrder: function (e) {
    wx.showLoading();
    var that = this;
    if (that.data.showAdress){
      if (that.data.curAddressData) {
        var said = that.data.curAddressData.SAId;
      } else {
        var said = 0;
      }
    }else{
      var said = 0;
    }
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,
      SelList: that.data.selList
    }
    //初始化优惠券
    wx.request({
      url: app.globalData.host + '/api/order/GetValidCouponList',
      data: {
        selList: that.data.selList,
        uid: app.globalData.userInfo.Uid
      }, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          return;
        }
        if (res.data.Data.length>0){
          that.setData({
            allCoupon: res.data.Data,
            curCoupon: res.data.Data[0]
          });
        }
      }
    })
    //初始化订单
    wx.request({
      url: app.globalData.host + '/api/order/confirmorderv2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0 && that.data.hasPay == false) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        }
        that.data.hasPay = true;
        //订单确认成功
        var confirm = that.processImageHost(res.data.Data);
        var curCoupon = that.data.curCoupon;
        if (curCoupon) {
          var payMoney = confirm.AllOrderAmount - curCoupon.Money;
          var payMoney = payMoney.toFixed(2);
          that.setData({
            payMoney: payMoney
          })
          console.log(payMoney);
        }
        that.setData({
          confirmOrder: confirm
        });
      }
    })
  },
  processImageHost: function (cart) {
    if (cart.StoreOrderList.length > 0) {
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartProductList.length; i++) {
        //主图
        cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg;
        if (cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length > 0) {
          for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length; j++) {
            //赠品图片
            cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg;
          }
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg;
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartSuitList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg;
        }
      }
    }
    return cart;

  },

  createOrder: function (e) {
    var that = this;
    var cashNew = e.detail.value.cash || 0//余额
    var formGold = e.detail.value.gold || 0//金币
    var formRemark = e.detail.value.remark || ""//备注
    var remark2 = "\t" + "联系人：" + e.detail.value.remark2; // 联系人
    var remark3 = "\t" + "手机号：" + e.detail.value.remark3; // 手机号
    if (this.data.showAdress) {//非自提
      remark2 = "";
      remark3 = "";
    } else {//自提
      // if (e.detail.value.remark2 == "") {
      //   wx.showModal({
      //     title: '提示',
      //     content: '自提请填写联系人',
      //     showCancel: false
      //   });
      //   return;
      // }
      // if (e.detail.value.remark3 == "") {
      //   wx.showModal({
      //     title: '提示',
      //     content: '自提请填写联系电话',
      //     showCancel: false
      //   });
      //   return;
      // }
      // if (e.detail.value.remark3 != ""){
      //   if (!util.vailPhone(e.detail.value.remark3)) {
      //     wx.showModal({
      //       title: '提示',
      //       content: '请输入正确的手机号！',
      //       showCancel: false
      //     });
      //     return;
      //   }
      // }
    }
    var myOrderData = that.data.myOrderData//选择优惠券
    var curCoupon = {}//默认优惠券
    var curCouponId = 0//优惠券id
    var curCouponMoney = 0//优惠券金额
    if (JSON.stringify(myOrderData) != "{}"){
       curCoupon = myOrderData//优惠券
       curCouponId = curCoupon.couponid
       curCouponMoney = curCoupon.money
    }else{
      if (that.data.curCoupon) {
         curCoupon = that.data.curCoupon//优惠券
         curCouponId = curCoupon.CouponId
         curCouponMoney = curCoupon.Money
      }
    }
    var PayCreditPrice = that.data.confirmOrder.PayCreditPrice//积分价格
    if (formGold) {
      var PayCredits = formGold / 100 * PayCreditPrice//积分金额
    } else {
      var PayCredits = 0
    }
    var AllOrderAmount = that.data.confirmOrder.AllOrderAmount//订单总额
    var AllFullCut = that.data.confirmOrder.AllFullCut//满减
    var countMoney = parseFloat(curCouponMoney) + parseFloat(AllFullCut) + parseFloat(PayCredits) + parseFloat(cashNew)//优惠总和
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    if (!uid) {
      wx.showModal({
        title: '提示',
        content: '获取用户信息失败',
        showCancel: false
      })
      return;
    }
    if (!that.data.showAdress){
      var AdressSaid = 0
    }else{
      if (that.data.curAddressData == null || !that.data.curAddressData.SAId) {
        wx.showModal({
          title: '请填写地址信息',
          content: '',
          showCancel: false
        });
        return;
      }
      var AdressSaid = that.data.curAddressData.SAId
    }
    wx.showLoading();
    console.log(AdressSaid)
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: AdressSaid,//配送地址id
      SelList: that.data.selList,//选中的购物车项键列表
      PayCreditCount: parseFloat(formGold),//支付积分
      PayCash: parseFloat(cashNew),//余额支付
      CouponIdList: curCouponId,//客户已经激活的优惠劵
      CouponSNList: '',//客户还未激活的优惠劵
      FullCut: that.data.confirmOrder.AllFullCut,//验证满减金额
      BuyerRemark: formRemark + remark2 + remark3 //备注
    }
    console.log(postData)
    wx.request({
      url: app.globalData.host + '/api/order/SubmitOrderV2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        console.log(res)
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        } else {
            // 下单成功，跳转到支付界面
            var oid = res.data.Data;
            wxpay.wxpay(app, oid, "/pages/order-list/index");
            return;
        }
      }
    })
  },
  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetDefaultShipAddress',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: (res) => {
        if (res.data.Code == 0) {
          that.setData({
            curAddressData: res.data.Data
          });
        }
        this.confirmOrder();
      }
    })
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index?said=0"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  selectCoupon: function () {
    wx.navigateTo({
      url: "/pages/member/coupon/index?st=1&sl=" + this.data.selList
    })
  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    var that = this;
    wx.showLoading({
      title: '正在刷新',
      success: function () {
        that.confirmOrder()
      }
    })

    wx.stopPullDownRefresh();
  }
})
